<template>
  <div class="bg-white rounded-lg shadow-lg p-6">
    <h2 class="text-2xl font-semibold text-gray-800 mb-6">实践任务</h2>
    
    <!-- 如果没有选择指南，显示指南列表 -->
    <div v-if="!selectedGuide">
      <!-- 任务统计 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="bg-blue-50 rounded-lg p-4 text-center">
          <div class="text-2xl font-bold text-blue-600 mb-2">{{ guides.length-2 }}</div>
          <div class="text-sm text-blue-800">总指南数</div>
        </div>
        <div class="bg-green-50 rounded-lg p-4 text-center">
          <div class="text-2xl font-bold text-green-600 mb-2">{{ completedCount }}</div>
          <div class="text-sm text-green-800">已完成</div>
        </div>
        <div class="bg-orange-50 rounded-lg p-4 text-center">
          <div class="text-2xl font-bold text-orange-600 mb-2">{{ pendingCount-2 }}</div>
          <div class="text-sm text-orange-800">待完成</div>
        </div>
      </div>

      <!-- 指南列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="guide in guides"
          :key="guide.id"
          class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 cursor-pointer transform hover:scale-105 border border-gray-200"
          @click="selectGuide(guide)"
        >
          <div class="p-6">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-xl font-semibold text-gray-800">{{ guide.title }}</h3>
              <div class="flex items-center space-x-2">
                <span class="px-2 py-1 text-xs rounded-full" :class="guide.osClass">
                  {{ guide.os }}
                </span>
                <span :class="[
                  'px-2 py-1 rounded-full text-xs font-medium',
                  guide.status === 'completed' ? 'bg-green-100 text-green-800' :
                  guide.status === 'in-progress' ? 'bg-blue-100 text-blue-800' :
                  'bg-gray-100 text-gray-800'
                ]">
                  {{ getStatusText(guide.status) }}
                </span>
              </div>
            </div>
            <p class="text-gray-600 mb-4">{{ guide.description }}</p>
            <div class="flex items-center justify-between">
              <span class="text-sm text-gray-500">{{ guide.estimatedTime }}</span>
              <button class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors">
                查看指南
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 如果选择了指南，显示markdown内容 -->
    <div v-else class="max-w-6xl mx-auto">
      <div class="bg-white rounded-lg shadow-lg">
        <!-- 指南头部 -->
        <div class="border-b border-gray-200 p-6">
          <div class="flex items-center justify-between">
            <div>
              <h2 class="text-2xl font-bold text-gray-800">{{ selectedGuide.title }}</h2>
              <p class="text-gray-600 mt-1">{{ selectedGuide.description }}</p>
              <div class="flex items-center mt-2 space-x-4">
                <span class="px-2 py-1 text-xs rounded-full" :class="selectedGuide.osClass">
                  {{ selectedGuide.os }}
                </span>
                <span class="text-sm text-gray-500">预计时间：{{ selectedGuide.estimatedTime }}</span>
              </div>
            </div>
            <button
              @click="goBack"
              class="px-4 py-2 bg-gray-500 hover:bg-gray-600 text-white rounded-md transition-colors"
            >
              返回列表
            </button>
          </div>
        </div>
        
        <!-- markdown内容 -->
        <div class="p-6">
          <div class="h-[600px] overflow-y-auto border border-gray-200 rounded-lg bg-gray-50">
            <div v-if="loading" class="text-center py-8">
              <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
              <p class="mt-2 text-gray-600">加载中...</p>
            </div>
            <div v-else-if="error" class="text-center py-8">
              <p class="text-red-600">{{ error }}</p>
            </div>
            <div id="markdown-content" v-else class="prose prose-lg max-w-none p-6 bg-white" v-html="markdownContent"></div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 环境检查工具 -->
    <div class="mt-8 bg-gray-50 rounded-lg p-6">
      <h3 class="text-lg font-semibold text-gray-800 mb-4">开发环境检查</h3>
      <p class="text-gray-600 mb-4">在开始作业前，请确保您的开发环境配置正确：</p>
      
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div v-for="tool in environmentTools" :key="tool.name" 
             class="flex items-center justify-between p-3 bg-white rounded border">
          <div class="flex items-center">
            <!-- 状态图标 -->
            <div class="w-5 h-5 mr-2 flex items-center justify-center">
              <!-- 安装成功 -->
              <svg v-if="tool.status === 'installed'" class="w-5 h-5 text-green-500" 
                   fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" 
                      d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" 
                      clip-rule="evenodd" />
              </svg>
              <!-- 未安装 -->
              <svg v-else-if="tool.status === 'not-installed'" class="w-5 h-5 text-red-500" 
                   fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" 
                      d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" 
                      clip-rule="evenodd" />
              </svg>
              <!-- 检查中 -->
              <svg v-else-if="tool.status === 'checking'" class="w-5 h-5 text-blue-500 animate-spin" 
                   fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" 
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <!-- 检查失败 -->
              <svg v-else-if="tool.status === 'error'" class="w-5 h-5 text-yellow-500" 
                   fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" 
                      d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" 
                      clip-rule="evenodd" />
              </svg>
            </div>
            <span class="font-medium">{{ tool.name }}</span>
          </div>
          <span class="text-sm" :class="{
            'text-green-600': tool.status === 'installed',
            'text-red-600': tool.status === 'not-installed',
            'text-blue-600': tool.status === 'checking',
            'text-yellow-600': tool.status === 'error'
          }">
            {{ tool.version || getStatusText(tool.status) }}
          </span>
        </div>
      </div>
      
      <button @click="checkEnvironment" 
              class="mt-4 bg-blue-500 text-white px-4 py-2 mr-6 rounded hover:bg-blue-600 transition-colors">
        在线检查环境
      </button>
      <button @click="downloadOfflineChecker" 
              class="mt-2 bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition-colors">
        离线检查
      </button>
      <p class="mt-3 text-sm text-gray-600">
        <span class="text-orange-600 font-medium">注意:</span> 如果使用在线检查，请先在本地开启后台服务 
        <code class="bg-gray-100 px-1 py-0.5 rounded text-xs">/api/check-environment</code>
      </p>
    </div>
  </div>
</template>

<style scoped>
/* Markdown 内容样式 */
:deep(#markdown-content h1),
:deep(#markdown-content h2),
:deep(#markdown-content h3),
:deep(#markdown-content h4),
:deep(#markdown-content h5),
:deep(#markdown-content h6) {
  font-weight: bold !important;
}

:deep(#markdown-content a) {
  color: #3b82f6 !important;
  text-decoration: underline !important;
}

:deep(#markdown-content table) {
  border-collapse: collapse !important;
  border: 1px solid #d1d5db !important;
}

:deep(#markdown-content table th),
:deep(#markdown-content table td) {
  border: 1px solid #d1d5db !important;
  padding: 8px 12px !important;
}

:deep(#markdown-content table th) {
  background-color: #f9fafb !important;
}
</style>

<script setup>
import { ref, computed } from 'vue'
import { marked } from 'marked'

// 配置marked
marked.setOptions({
  breaks: true,
  gfm: true
})

// 指南数据
const guides = ref([
  {
    id: 1,
    title: 'Windows开发环境搭建',
    description: '在Windows系统上搭建完整的前端开发环境，包括Git、Node.js、VS Code等工具的安装和配置',
    os: 'Windows',
    osClass: 'bg-blue-100 text-blue-800',
    estimatedTime: '30-45分钟',
    status: 'pending',
    filePath: '/chap02/build_env.md'
  },
  {
    id: 2,
    title: 'Windows详细搭建指南',
    description: '详细的Windows前端开发环境搭建指南，包含完整的安装步骤、配置说明和常见问题解决方案',
    os: 'Windows',
    osClass: 'bg-blue-100 text-blue-800',
    estimatedTime: '45-60分钟',
    status: 'pending',
    filePath: '/chap02/Guide.md'
  },
  {
    id: 3,
    title: 'macOS开发环境搭建',
    description: '在macOS系统上搭建前端开发环境，包括Homebrew、Git、Node.js、VS Code等工具的安装和优化配置',
    os: 'macOS',
    osClass: 'bg-gray-100 text-gray-800',
    estimatedTime: '40-55分钟',
    status: 'pending',
    filePath: '/chap02/Guide4Mac.md'
  }
])

// 当前选择的指南和状态
const selectedGuide = ref(null)
const markdownContent = ref('')
const loading = ref(false)
const error = ref('')

// 环境检查工具
const environmentTools = ref([
  { name: 'Node.js', status: 'installed', version: 'v18.17.0' },
  { name: 'npm', status: 'installed', version: 'v9.6.7' },
  { name: 'Vue CLI', status: 'installed', version: 'v5.0.8' },
  { name: 'Git', status: 'installed', version: 'v2.41.0' },
  { name: 'VS Code', status: 'installed', version: 'v1.84.2' },
  { name: 'Chrome DevTools', status: 'installed', version: 'Latest' }
])

// 计算属性
const completedCount = computed(() => 
  guides.value.filter(g => g.status === 'completed').length
)

const pendingCount = computed(() => 
  guides.value.filter(g => g.status === 'pending').length
)

// 方法
const getStatusText = (status) => {
  const statusMap = {
    'completed': '已完成',
    'in-progress': '进行中',
    'pending': '待开始',
    'overdue': '已逾期',
    'installed': '已安装',
    'not-installed': '未安装',
    'checking': '检查中',
    'error': '检查失败'
  }
  return statusMap[status] || status
}

const selectGuide = async (guide) => {
  selectedGuide.value = guide
  await loadMarkdownContent(guide.filePath)
}

const loadMarkdownContent = async (filePath) => {
  loading.value = true
  error.value = ''
  
  try {
    const response = await fetch(filePath)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const text = await response.text()
    markdownContent.value = marked(text)
  } catch (err) {
    console.error('加载Markdown文件失败:', err)
    error.value = '加载指南内容失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  selectedGuide.value = null
  markdownContent.value = ''
  error.value = ''
}

const checkEnvironment = async () => {
  console.log('开始检查开发环境...')
  
  // 重置所有工具状态为检查中
  environmentTools.value.forEach(tool => {
    tool.status = 'checking'
    tool.version = '检查中...'
  })
  
  try {
    // 调用后端环境检查API
    const response = await fetch('/api/check-environment')
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    
    if (data.success) {
      // 更新工具状态
      data.tools.forEach(apiTool => {
        const localTool = environmentTools.value.find(tool => tool.name === apiTool.name)
        if (localTool) {
          localTool.status = apiTool.status
          localTool.version = apiTool.version
        }
      })
      console.log('环境检查完成')
    } else {
      throw new Error(data.error || '环境检查失败')
    }
  } catch (error) {
    console.error('环境检查失败:', error)
    
    // 如果API调用失败，将所有工具状态设为错误
    environmentTools.value.forEach(tool => {
      tool.status = 'error'
      tool.version = '检查失败 - ' + (error.message || '网络错误')
    })
  }
}

const downloadOfflineChecker = () => {
  const link = document.createElement('a')
  link.href = '/chap01/check-env.bat'
  link.download = 'check-env.bat'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 导出方法供模板使用
defineExpose({
  downloadOfflineChecker
})
</script>